package com.southwind.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int width = 100, height = 34;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.LIGHT_GRAY);
        g.fillRect(0, 0, width, height);

        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder captcha = new StringBuilder();
        Random rand = new Random();

        for (int i = 0; i < 4; i++) {
            char ch = chars.charAt(rand.nextInt(chars.length()));
            captcha.append(ch);
            g.setColor(Color.BLACK);
            g.drawString(String.valueOf(ch), 20 * i + 10, 24);
        }

        // 保存验证码到 session
        request.getSession().setAttribute("captcha", captcha.toString());

        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
}
